/*
 * @Description:
 * @Author: maskMan
 * @LastEditTime: 2024-11-20 18:39:13
 */
import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Route } from 'vue-router';
import { ManagerModule } from '@/store/modules/manager';
import { PermissionModule } from './store/modules/permission';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/404'];

router.beforeEach(async (to: Route, from: Route, next: any) => {
  // Start progress bar
  NProgress.start();
  // Check if user is logged in (has token)
  if (ManagerModule.token) {
    if (to.path == '/404') {
      if (from.path == '/404') {
        next(false);
      } else {
        next();
      }
    } else if (to.path === '/login') {
      // If logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done();
    } else {
      // If user has no roles, fetch user roles
      if (!ManagerModule.roles) {
        try {
          // Fetch user roles
          const ret = await ManagerModule.GetManagerRoles();
          if (ret) {
            PermissionModule.GenerateRoutes();
            //Dynamically add accessible routes
            PermissionModule.dynamicRoutes.forEach((route) => {
              router.addRoute(route);
            });
            router.replace('/dashboard');
          } else {
            // If roles fetching failed, reset token and redirect to login
            ManagerModule.ResetToken();
            router.replace(`/`);
            NProgress.done();
          }
        } catch (err) {
          // On error, reset token and redirect to login
          ManagerModule.ResetToken();
          router.replace(`/`);
          NProgress.done();
        }
      } else {
        if (to.path == '/login') {
          ManagerModule.ResetToken();
          next();
        } else {
          next();
        }
      }
    }
  } else {
    // If no token (user is not logged in)
    if (whiteList.indexOf(to.path) !== -1) {
      // If the route is in the whitelist, allow access
      ManagerModule.ResetToken();
      next();
    } else {
      // For all other routes, redirect to login
      ManagerModule.ResetToken();
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});
router.afterEach((to: any) => {
  // Finish progress bar
  NProgress.done();

  // set page title
  // document.title = to.meta.title;
});
